package com.liu.stockmarket.ui.datacenter

import androidx.lifecycle.*
import com.liu.stockmarket.model.NewBond
import com.liu.stockmarket.model.QuotationResult
import com.liu.stockmarket.repository.network.EasyMoneyRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class DataCenterViewModel(private val easyMoneyRepository: EasyMoneyRepository) : ViewModel() {

    private val _index = MutableLiveData<Int>()
    val text: LiveData<String> = Transformations.map(_index) {
        "Hello world from section: $it"
    }

    private val _bonds= MutableLiveData<List<NewBond>>()
    val bonds:LiveData<List<NewBond>> = _bonds

    private val _quotationResult= MutableLiveData<QuotationResult>()
    val quotationResult:LiveData<QuotationResult> = _quotationResult

    fun setIndex(index: Int) {
        _index.value = index
    }

    fun getNewBond(pageNumber:Int) {
        viewModelScope.launch (Dispatchers.IO){
            val newBond = easyMoneyRepository.getNewBond(pageNumber)
            if (newBond != null && newBond.success) {
                _bonds.postValue(newBond.result.data)

            }
        }
    }

    fun getQuotation() {
        viewModelScope.launch(Dispatchers.IO) {
            val quotation = easyMoneyRepository.getQuotation()
            quotation?.let {
                _quotationResult.postValue(it)
            }

        }
    }

    class DataCenterViewModelFactory(
        private val easyMoneyRepository: EasyMoneyRepository,
    ) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return DataCenterViewModel(
                easyMoneyRepository
            ) as T
        }

    }


}